<template>
  <div>
    <div class="L2TPPPTPContent">
      <div style="min-width:400px;display: flex;flex-direction: column;justify-content: center;align-items: center;">
        <el-form ref="form" :model="record" :inline='true' label-width="0" :rules="rules" :show-message='false'>
          <el-descriptions title="" size="mini" :column='1' border contentClassName='linkConfigDescriptionsItem' labelClassName='l2tpLabelName'>
            <el-descriptions-item :label="$t('是否启用')" :labelStyle="{ 'text-align': 'center' }">
              <el-radio-group v-model="record.switch">
                <el-radio label="on" class="on">{{$t('启 用')}}</el-radio>
                <el-radio label="off" class="off">{{$t('禁 用')}}</el-radio>
              </el-radio-group>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('协议类型')" :labelStyle="{ 'text-align': 'center' }">
              <el-radio-group v-model="record.protocol">
                <el-radio label="l2tp" class="l2tp">L2TP</el-radio>
                <el-radio label="pptp" class="pptp">PPTP</el-radio>
              </el-radio-group>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('工作模式')" :labelStyle="{ 'text-align': 'center' }">
              <el-radio-group v-model="record.mode" @change="modeChange">
                <el-radio label="server" class="server">{{$t('服务端')}}</el-radio>
                <el-radio label="client" class="client">{{$t('客户端')}}</el-radio>
              </el-radio-group>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('用户名')" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="user_name" key="user_name">
                <el-input v-emoji v-model="record.user_name" ref="userName" style="width:278px;line-height: 28px;" :maxlength="127" size='mini'></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('密码')" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="user_passwd" key="user_passwd">
                <el-input v-emoji v-model="record.user_passwd" ref="userPasswd" style="width:278px;" :maxlength="127" size='mini' @focus="handleFocus" @blur="handleBlur" class="inputPsd"></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('服务器地址')" v-if="record.mode === 'client'" :labelStyle="{ 'text-align': 'center' }">
              <el-input v-emoji v-model="record.server_address" ref="serverAddress" style="width:278px;" size='mini'></el-input>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('客户端DNS地址')" v-if="record.mode === 'server'" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="dns_address" key="dns_address">
                <el-input v-emoji v-model="record.dns_address" ref="dnsAddress" style="width:278px;" size='mini'></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('客户端地址池')" v-if="record.mode === 'server'" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="pool_left_address" key="pool_left_address">
                <el-input v-emoji v-model="record.pool_left_address" ref="leftAddress" style="width:132px;" size='mini'></el-input>
              </el-form-item>
              ~
              <el-form-item prop="pool_right_address" key="pool_right_address">
                <el-input v-emoji v-model="record.pool_right_address" ref="rightAddress" style="width:132px;" size='mini'></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('服务端地址池')" v-if="record.mode === 'server'" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="local_left_address" key="local_left_address">
                <el-input v-emoji v-model="record.local_left_address" ref="local" style="width:132px;" size='mini'></el-input>
              </el-form-item>
              ~
              <el-form-item prop="local_right_address" key="local_right_address">
                <el-input v-emoji v-model="record.local_right_address" ref="localRight" style="width:132px;" size='mini'></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('VPN接口MTU')" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="mtu" key="mtu">
                <el-input v-emoji v-model="record.mtu" ref="mtu" style="width:278px;" size='mini'></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('组网模式')" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="networking_mode" key="networking_mode">
                <el-select v-model="record.networking_mode" ref="networking" :placeholder="$t('请选择')" style="width:258px;" size='mini'>
                  <el-option key="site_to_site" :label="$t('站点到站点')" value="site_to_site"></el-option>
                  <el-option key="pc_to_site" :label="$t('pc到站点')" value="pc_to_site" v-if="record.mode === 'server'"></el-option>
                </el-select>
                <el-tooltip class="item recordMode" effect="light"  :content="$t('站点到站点模式，只允许接入一个客户端')" v-if="record.mode === 'server'" placement="top">
                  <i class="el-icon-warning-outline" style="color:#FF0000;font-size:16px;"></i>
                </el-tooltip>
                <el-tooltip class="item recordModes" effect="light" :content="$t('仅支持站点到站点模式')" v-if="record.mode === 'client'" placement="top">
                  <i class="el-icon-warning-outline" style="color:#FF0000;font-size:16px;"></i>
                </el-tooltip>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('对端子网地址')" v-if="record.networking_mode === 'site_to_site'" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="peer_network_addr" key="peer_network_addr">
                <el-input v-emoji v-model="record.peer_network_addr" ref="addr" style="width:278px;" size='mini'></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('对端子网掩码')" v-if="record.networking_mode === 'site_to_site'" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="peer_network_mask" key="peer_network_mask">
                <el-input v-emoji v-model="record.peer_network_mask" ref="mask" style="width:278px;" size='mini'></el-input>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('通过VPN上网')" v-if="record.networking_mode === 'pc_to_site'" :labelStyle="{ 'text-align': 'center' }">
              <el-radio-group v-model="record.vpn_to_internet">
                <el-radio label="on" class="on">{{$t('启 用')}}</el-radio>
                <el-radio label="off" class="off">{{$t('禁 用')}}</el-radio>
              </el-radio-group>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('上网的出接口')" v-if="record.vpn_to_internet === 'on' && record.networking_mode === 'pc_to_site'" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="internet_out_interface" key="internet_out_interface">
                <el-select v-model="record.internet_out_interface" :placeholder="$t('请选择')" ref="interface" size='mini' style="width:258px;" :disabled='record.vpn_to_internet === "off" || record.switch === "off"' filterable @change="internetOutInterfaceChange">
                  <el-option v-for="item in internetOutInterfaceList" :key="item.strPhysicsName" :label="item.strPhysicsName" :value="item.strPhysicsName"></el-option>
                </el-select>
                <el-tooltip class="item top" effect="light"  :content="$t('上网接口处选择管理口时，须在自身防护界面打开允许管理口进行业务面处理按钮')" placement="top">
                  <i class="el-icon-warning-outline" style="color:#FF0000;font-size:16px;"></i>
                </el-tooltip>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item :label="$t('上网的出接口ip')" v-if="record.vpn_to_internet === 'on' && record.networking_mode === 'pc_to_site'" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="internet_out_ip" key="internet_out_ip">
                <el-select v-model="record.internet_out_ip" ref="outIp" :placeholder="$t('请选择')" size='mini' style="width:258px;" :disabled='record.vpn_to_internet === "off" || record.switch === "off"' filterable>
                  <el-option v-for="item in restaurants" :key="item.cPortIpv4" :label="item.cPortIpv4" :value="item.cPortIpv4"></el-option>
                </el-select>
                <el-tooltip class="item top" effect="light"  :content="$t('请在上网的出接口上配置IP')" placement="top">
                  <i class="el-icon-warning-outline" style="color:#FF0000;font-size:16px;"></i>
                </el-tooltip>
              </el-form-item>
              <!-- <el-autocomplete class="inline-input" v-model="record.internet_out_ip" :fetch-suggestions="querySearch" size='mini' style="width:278px;" :disabled='record.vpn_to_internet === "off" || record.switch === "off"'></el-autocomplete> -->
            </el-descriptions-item>
            <el-descriptions-item :label="$t('上网的网关ip')" v-if="record.vpn_to_internet === 'on' && record.networking_mode === 'pc_to_site'" :labelStyle="{ 'text-align': 'center' }">
              <el-form-item prop="internet_next_hop" key="internet_next_hop">
                <el-input v-emoji v-model="record.internet_next_hop" ref="nextHop" style="width:278px;" size='mini' :disabled='record.vpn_to_internet === "off" || record.switch === "off"'></el-input>
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
        </el-form>
      </div>
    </div>
    <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
      <el-button type="primary" @click="submit" style="margin-top:10px;" class="submit">{{$t('保 存')}}</el-button>
    </div>
  </div>
</template>
<script>
import { getL2TPPPTPInfo, saveL2TPPPTPInfo } from '@/api/network/l2tp/l2tp-pptp'
import { getPhysicalApiArray } from '@/api/network/api/physical'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'LinkConfig',
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        this.$messages.error(this.$t('不能为空'))
        callback(new Error())
      } else {
        callback()
      }
    }
    var validateMtu = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!this.isInteger(value)) {
        this.$messages.error(this.$t('只能输入整数'))
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) > 9216 || Number(value) < 68) {
        this.$messages.error(this.$t('范围在68到9216之间'))
        callback(new Error(this.$t('范围在68到9216之间')))
      } else {
        callback()
      }
    }
    var validateIp = (rule, value, callback) => {
      let ipv4 = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      if (String(value).trim() === '') {
        this.$messages.error(this.$t('不能为空'))
        callback(new Error())
      } else if (ipv4.test(value)) {
        callback()
      } else {
        this.$messages.error(this.$t('IP格式不正确'))
        callback(new Error(this.$t('IP格式不正确')))
      }
    }
    var validateMask = (rule, value, callback) => {
      if (String(value).trim() === '') {
        this.$messages.error(this.$t('不能为空'))
        callback(new Error())
      } else if (!this.isValidMask(value)) {
        this.$messages.error(this.$t('子网掩码格式不正确'))
        callback(new Error(this.$t('子网掩码格式不正确')))
      } else {
        callback()
      }
    }
    return {
      record: {
        switch: 'off',
        protocol: 'l2tp',
        mode: 'server',
        user_name: '',
        user_passwd: '',
        dns_address: '',
        server_address: '',
        pool_left_address: '',
        pool_right_address: '',
        local_left_address: '',
        local_right_address: '',
        mtu: '1500',
        networking_mode: 'site_to_site',
        peer_network_addr: '',
        peer_network_mask: '',
        vpn_to_internet: 'on',
        internet_out_interface: '',
        internet_out_ip: '',
        internet_next_hop: ''
      },
      networkingModeList: {
        'site_to_site': '站点到站点',
        'pc_to_site': 'pc到站点'
      },
      internetOutInterfaceList: [],
      restaurants: [],
      rules: {
        user_name: [{ required: false, validator: validateName, trigger: 'blur' }],
        user_passwd: [{ required: false, validator: validateName, trigger: 'blur' }],
        dns_address: [{ required: false, validator: validateName, trigger: 'blur' }],
        mtu: [{ required: false, validator: validateMtu, trigger: 'blur' }],
        pool_left_address: [{ required: false, validator: validateName, trigger: 'blur' }],
        pool_right_address: [{ required: false, validator: validateName, trigger: 'blur' }],
        local_left_address: [{ required: false, validator: validateName, trigger: 'blur' }],
        local_right_address: [{ required: false, validator: validateName, trigger: 'blur' }],
        peer_network_addr: [{ required: false, validator: validateIp, trigger: 'blur' }],
        peer_network_mask: [{ required: false, validator: validateMask, trigger: 'blur' }],
        internet_out_interface: [{ required: false, validator: validateName, trigger: 'change' }],
        internet_out_ip: [{ required: false, validator: validateName, trigger: 'change' }],
        internet_next_hop: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  created () {
    getL2TPPPTPInfo().then(res => {
      if (res.status === 0) {
        this.record = Object.assign(this.record, res.info[0])
        getPhysicalApiArray().then(res1 => {
          this.internetOutInterfaceList = res1.info
          if (!this.record.internet_out_interface) {
            this.record.internet_out_interface = res1.info[0].strPhysicsName
          }
          for (let item of this.internetOutInterfaceList) {
            if (this.record.internet_out_interface === item.strPhysicsName) {
              if (item.ipv4 && item.ipv4[0].cPortIpv4) {
                this.restaurants = item.ipv4
              }
              break
            }
          }
        })
      }
    })
  },
  mounted () {
    this.$nextTick(() => {
      const data = ['userName', 'userPasswd', 'dnsAddress', 'leftAddress', 'rightAddress', 'local', 'localRight', 'mtu', 'addr', 'mask']
      const selectData = ['networking']
      inputClass(this.$refs, data)
      selectClass(this.$refs, selectData)
    })
  },
  computed: {
    change () {
      const { vpn_to_internet, networking_mode } = this.record
      return { vpn_to_internet, networking_mode }
    }
  },
  watch: {
    change (val) {
      if (val.vpn_to_internet === 'on' && val.networking_mode === 'pc_to_site') {
        this.$nextTick(() => {
          const selectData = ['interface', 'outIp']
          selectClass(this.$refs, selectData)
          const data = ['nextHop']
          inputClass(this.$refs, data)
        })
      }
    },
    'record.mode' (val) {
      if (val === 'client') {
        this.$nextTick(() => {
          const data = ['serverAddress', 'mtu']
          const selectData = ['networking']
          inputClass(this.$refs, data)
          selectClass(this.$refs, selectData)
        })
      } else if (val === 'server') {
        this.$nextTick(() => {
          const data = ['dnsAddress', 'leftAddress', 'rightAddress', 'local', 'mtu']
          const selectData = ['networking']
          inputClass(this.$refs, data)
          selectClass(this.$refs, selectData)
        })
      }
    }
  },
  methods: {
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          saveL2TPPPTPInfo(this.record).then(res => {
            if (res.status === 0) {
              this.$message({
                message: this.$t('应用成功'),
                type: 'success'
              })
            }
          })
        }
      })
    },
    internetOutInterfaceChange (value) {
      this.restaurants = []
      this.record.internet_out_ip = ''
      for (let item of this.internetOutInterfaceList) {
        if (value === item.strPhysicsName) {
          if (item.ipv4 && item.ipv4[0].cPortIpv4) {
            this.restaurants = item.ipv4
          }
          break
        }
      }
    },
    modeChange (value) {
      if (value === 'client') {
        this.record.networking_mode = 'site_to_site'
      }
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    },
    handleFocus () {
      this.$refs.password = 'password'
    },
    handleBlur () {
      this.$refs.password = 'text'
    },
    // 验证子网掩码
    isValidMask (mask) {
      let reg = /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(255|254|252|248|240|224|192|128|0)$/
      return reg.test(mask)
    }
    // querySearch (queryString, cb) {
    //   var restaurants = this.restaurants
    //   var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
    //   // 调用 callback 返回建议列表的数据
    //   cb(results)
    // },
    // createFilter (queryString) {
    //   return (restaurant) => {
    //     return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
    //   }
    // }
  }
}
</script>
<style lang="less">
.l2tpLabelName {
  width: 150px;
  height: 42px;
}

.linkConfigDescriptionsItem {
  width: 300px;
  height: 42px;
}

.L2TPPPTPContent {
  margin: 20px;
  overflow-x: auto;

  .el-collapse-item__header {
    font-size: 18px;
    font-weight: 600;
  }

  .el-collapse-item__content {
    margin-left: 20px;
  }

  .el-form-item {
    margin: 0;
    border: 0;
    padding: 0;
  }

  .el-form-item__content {
    line-height: 28px;
  }
}
</style>
<style lang="scss" scoped>
.inputPsd {
  -webkit-text-security: disc;
}
</style>
